package uk.ac.glasgow.demosocs.impl;

import java.io.Serializable;
import java.util.SortedMap;
import java.util.TreeMap;
import uk.ac.glasgow.demosocs.RankedVote;

/**
 * A ranked vote, representing an instance that may be cast in an election.
 *
 */

public class RankedVoteImpl implements RankedVote, Serializable {

	private TreeMap<Integer, String> preferences;

	private static final long serialVersionUID = 1L;

	/**
	 * This maps each vote to a preference.
	 * @param preferences Unknown number of candidates which have 
	 * been voted for.
	 */
	public RankedVoteImpl(String... preferences) {
		this.preferences = new TreeMap<Integer, String>();

		for (int i = 0; i < preferences.length; i++)
			this.preferences.put(i, preferences[i]);
	}

	private RankedVoteImpl(TreeMap<Integer, String> preferences) {
		this.preferences = preferences;
	}

	public String getTopPreference() {
		if (size() > 0)
			return preferences.firstEntry().getValue();
		else
			return null;
	}

	public int size() {
		return preferences.size();
	}

	public RankedVoteImpl getTailPreferences() {
		if (size() > 1) {
			Integer highestPreference = preferences.firstKey();
			Integer nextPreference = preferences.higherKey(highestPreference);

			SortedMap<Integer, String> lower = preferences.tailMap(nextPreference);

			return new RankedVoteImpl(new TreeMap<Integer, String>(lower));
		} else
			return null;
	}


	public String toString() {
		return preferences.toString();
	}

	public TreeMap<Integer, String> getPreferences() {
		return preferences;
	}

	public void setPreferences(TreeMap<Integer, String> preferences) {
		this.preferences = preferences;
	}
	
	
	public void removeCandidate(String s){
		preferences.remove(s);
	}
	
}
